import {
  ModalForm,
  ProFormCheckbox,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import * as React from 'react';
import { useRef, useState } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useAsyncEffect } from 'ahooks';
import type { GithubIssueItem } from '../index';
import { Form, Select, message } from 'antd';
import { getBuildingsList, getBuildingsView, getRoomTypeList } from '../../BuildingType/request';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { postRoomsBatchAdd, postRoomsEdit } from '../request';
import { GenerateRoom } from '../utils';
import { useIntl } from '@umijs/max';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const AddOneRoom = (props: {
  visible: boolean;
  id: number;
  info: GithubIssueItem | null;
  onCancel: () => void;
  done: () => void;
}) => {
  const { visible, id, onCancel, done, info } = props;

  const formRef = useRef<ProFormInstance>(null);

  const formItemLayout = {
    labelCol: { span: 5 },
  };

  const intl = useIntl()

  useAsyncEffect(async () => {
    await waitTime(50);

    if (visible && id) {
      if (info) {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        buildingChange(info.buildingId);
        formRef?.current?.setFieldsValue({ ...info });
      }
    }
  }, [visible, id]);

  const onFinish = async (values: GithubIssueItem): Promise<boolean> => {
    await waitTime(500);
    console.log(values);

    const {
      data: { bno },
    } = await getBuildingsView(Number(values.buildingId));
    console.log(bno);

    const data = GenerateRoom({
      buildingId: values.buildingId,
      floor: String(values.floor),
      roomTypeId: Number(values.roomTypeId),
      roomNo: values.roomNo,
      roomName: values.roomName,
      lockType: values.lockType,
      isSuite: values.isSuite ? true : false,
      subRoomCount: values.subRoomCount,
      buildingName: bno,
    });
    console.log(data);

    if (!values.isSuite) {
   
      const res: any = await postRoomsEdit({...data,roomClass:values.roomType});
      console.log("新增",res);
      if (res.code !== 0) return message.error(res.msg);
      message.success(res.msg);
    } else {
      const res: any = await postRoomsBatchAdd(data);
      console.log("修改",res);
      if (res.code !== 0) return message.error(res.msg);
      message.success(res.msg);
    }

    onCancel();
    done();
    return true;
  };

  // 获取楼层列表---根据选择的楼栋获取楼栋对应下的楼层
  const [floorList, setFloorList] = useState([]);
  const buildingChange = async (e: number) => {
    formRef?.current?.setFieldsValue({ floor: '' });
    const res = await getBuildingsView(e);
    if (res.data.floor) {
      setFloorList(
        res.data.floor.split(',').map((v: any, index: number) => {
          return {
            label: v,
            value: v.length <= 2 ? v[0] : String(v[0]) + v[1],
            key: index,
          };
        }),
      );
      console.log(floorList);
    }
  };

  // 是否套房状态
  const [isStatus, setIsStatus] = useState(false);
  // 是否套房发生变化时
  const isSuiteChange = (e: CheckboxChangeEvent) => {
    setIsStatus(e.target.checked);
    formRef?.current?.setFieldsValue({ subRoomCount: '' });
  };

  return (
    <ModalForm<GithubIssueItem>
      {...formItemLayout}
      layout={'horizontal'}
      formRef={formRef}
      open={visible}
      title={id ? intl.formatMessage({id:"RoomSettings.Modify the room"}) : intl.formatMessage({id:"RoomSettings.Add new room"})}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => onCancel(),
      }}
      submitTimeout={2000}
      onFinish={(values) => onFinish(values)}
      width={'600px'}
    >
      <div style={{ marginTop: '40px' }}></div>
      <ProFormSelect
        width="md"
        name="buildingId"
        label={intl.formatMessage({id:"FixLock.Building"})}
        request={async () => {
          const res = await getBuildingsList({});
          return res.data.list.map((v: any) => {
            return { label: `${v.bno}${intl.formatMessage({id:'FixLock.building'})}`, value: v.id };
          });
        }}
        onChange={buildingChange}
        placeholder={intl.formatMessage({id:'RoomSettings.Please select a building'})}
        rules={[{ required: true, message:  intl.formatMessage({id:'RoomSettings.Please select a building'})}]}
      />
      <ProFormSelect
        width="md"
        name="floor"
        label={intl.formatMessage({id:'FixLock.Floor'})}
        key="key"
        options={floorList}
        placeholder={intl.formatMessage({id:'FixLock.Please select a floor'})}
        rules={[{ required: true, message: intl.formatMessage({id:'FixLock.Please select a floor'}) }]}
      />
      <ProFormSelect
        width="md"
        name="roomType"
        label={intl.formatMessage({id:"RoomSettings.Room type"})}
        initialValue={"Room"}
        options={[
          { label: intl.formatMessage({id:"RoomSettings.room"}), value: "Room" },
          { label: intl.formatMessage({id:"RoomSettings.meeting rooms"}), value: "Meeting" },
          { label: intl.formatMessage({id:"RoomSettings.restaurant"}), value: "Dining" },
        ]}
        placeholder={intl.formatMessage({id:"RoomSettings.Please select lock type"})}
        rules={[{ required: true, message: intl.formatMessage({id:"RoomSettings.Please select lock type"}) }]}
      />
      <ProFormSelect
        width="md"
        name="roomTypeId"
        label={intl.formatMessage({id:'FixLock.Room Type'})}
        request={async () => {
          const res = await getRoomTypeList();
          if (res.data.list) {
            return res.data.list.map((v: any) => {
              return { label: v.name, value: v.id, key: v.id };
            });
          }
          return [];
        }}
        placeholder={intl.formatMessage({id:'RoomSettings.Please select the room type'})}
        rules={[{ required: true, message: intl.formatMessage({id:'RoomSettings.Please select the room type'}) }]}
      />
      {/* <ProFormText
        width="md"
        name="roomNo"
        label="房号"
        placeholder="请输入房号"
        rules={[{ required: true, message: '请输入房号' }]}
      /> */}
      <ProFormDigit
        width="md"
        name="roomNo"
        label={intl.formatMessage({id:'FixLock.Room number'})}
        placeholder={intl.formatMessage({id:'RoomSettings.Please enter your room number'})}
        rules={[{ required: true, message: intl.formatMessage({id:'RoomSettings.Please enter your room number'}) }]}
        min={1}
        max={255}
      />
      <ProFormText
        width="md"
        name="roomName"
        label={intl.formatMessage({id:'RoomSettings.Room name'})}
        placeholder={intl.formatMessage({id:'RoomSettings.Please enter Room name"'})}
        rules={[
          { required: true, message: intl.formatMessage({id:'RoomSettings.Please enter Room name"'}) },
          { max: 255, message: intl.formatMessage({id:'RoomSettings.between 1-255'}) },
        ]}
      />
      <ProFormSelect
        width="md"
        name="lockType"
        label={intl.formatMessage({id:"RoomSettings.Lock type"})}
        initialValue={2}
        options={[
          { label: intl.formatMessage({id:"RoomSettings.Single"}), value: 1 },
          { label: '2.4G', value: 2 },
          { label: 'BLE', value: 3 },
        ]}
        placeholder={intl.formatMessage({id:"RoomSettings.Please select lock type"})}
        rules={[{ required: true, message: intl.formatMessage({id:"RoomSettings.Please select lock type"}) }]}
      />
      <ProFormCheckbox name="isSuite" label={intl.formatMessage({id:'RoomSettings.Is suite'})} onChange={isSuiteChange} />
      {isStatus && (
        <ProFormText
          width="md"
          name="subRoomCount"
          label={intl.formatMessage({id:'RoomSettings.Number of bedrooms'})}
          placeholder={intl.formatMessage({id:'RoomSettings.Please enter the number of subrooms'})}
          rules={[{ required: true, message: intl.formatMessage({id:'RoomSettings.Please enter the number of subrooms'}) }]}
        />
      )}
    </ModalForm>
  );
};

export default AddOneRoom;
